/*
 * @author larry
 **/
!function(){

	// alias list
	var runtime = chrome.runtime,
		tabs = chrome.tabs,

	// local variable
		zepto_code = undefined,
		ActionMap = undefined;

	// load Zepto
	ajax('http://s.yunshipei.com/javascript/zepto-1.0.js',function(){
		zepto_code = this.responseText;
	});

	// action map
	ActionMap = {
		/**
		 * @type{any}  
		 * @description 用于显示console Panel
		 */
		//"showConsolePanel" : function(message){
		//	console.log(message);
		//	var evt = message.document.createEvent('KeyboardEvent',true,true);
		//	evt.initKeyboardEvent('keypress', true, true, null, 'Esc');
		//	console.log(message.document.dispatchEvent(evt));
		//},
		/**
		 * @type{any}  
		 * @description 执行js code
		 */
		"executeScript" : function(message){
			tabs.executeScript(message.tabId , {
				code : zepto_code
						+ ';!function($){\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'
						+ message.code
						+ '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}(window.Zepto)'
			});
		},
		/**
		 * @type{any}  
		 * @description 主要用于输出dev_tools page 中的日志,以便于调试.
		 */
		"undefined" : function(log){
			console.log(log);
		}
	};

	/**
	 * @args{any} 消息实体
	 * @description 发送的消息必须带有action属性 否则当做日志信息输出
	 */
	runtime.onMessage.addListener(onMessage);
	function onMessage(message , sender){
		ActionMap[message.action || 'undefined'].apply(this ,arguments);
	}


	// Utils
	function ajax(url , cb ,method){
		var xhr = new XMLHttpRequest(),
			method = method || 'GET';
		xhr.open(method , url);
		xhr.onreadystatechange = function(){
			if(xhr.status == 200 && xhr.readyState == 4){
				cb.call(xhr);
			}
		}
		xhr.send(null);
	}
}();